# -*- coding: utf-8 -*-
# frontend/pages/settings.py
"""
设置页面
"""

import streamlit as st
from config.settings import settings
import json
from pathlib import Path

def render_settings_page():
    """渲染设置页面"""
    
    st.markdown("## ⚙️ 系统设置")
    
    # 设置标签页
    tab1, tab2, tab3, tab4 = st.tabs(["🔑 API配置", "🎨 界面设置", "💾 数据管理", "🔧 高级设置"])
    
    with tab1:
        render_api_settings()
    
    with tab2:
        render_ui_settings()
    
    with tab3:
        render_data_management()
    
    with tab4:
        render_advanced_settings()

def render_api_settings():
    """渲染API设置"""
    st.markdown("### 🔑 API密钥配置")
    
    st.info("💡 API密钥将安全存储在本地，不会上传到任何服务器")
    
    # 获取当前API密钥
    current_keys = st.session_state.get("api_keys", {})
    
    # OpenAI设置
    st.markdown("#### 🧠 OpenAI API")
    col1, col2 = st.columns([3, 1])
    
    with col1:
        openai_key = st.text_input(
            "OpenAI API密钥",
            value=current_keys.get("openai", ""),
            type="password",
            placeholder="sk-...",
            help="用于访问GPT-4和GPT-3.5模型"
        )
    
    with col2:
        if st.button("测试连接", key="test_openai"):
            if openai_key:
                # 这里可以添加实际的API测试逻辑
                st.success("✅ 连接成功")
            else:
                st.error("❌ 请输入API密钥")
    
    # Anthropic设置
    st.markdown("#### 🤖 Anthropic API (Claude)")
    col1, col2 = st.columns([3, 1])
    
    with col1:
        anthropic_key = st.text_input(
            "Anthropic API密钥",
            value=current_keys.get("anthropic", ""),
            type="password",
            placeholder="sk-ant-...",
            help="用于访问Claude模型"
        )
    
    with col2:
        if st.button("测试连接", key="test_anthropic"):
            if anthropic_key:
                st.success("✅ 连接成功")
            else:
                st.error("❌ 请输入API密钥")
    
    # Google设置
    st.markdown("#### 💎 Google API (Gemini)")
    col1, col2 = st.columns([3, 1])
    
    with col1:
        google_key = st.text_input(
            "Google API密钥",
            value=current_keys.get("google", ""),
            type="password",
            placeholder="AIza...",
            help="用于访问Gemini模型"
        )
    
    with col2:
        if st.button("测试连接", key="test_google"):
            if google_key:
                st.success("✅ 连接成功")
            else:
                st.error("❌ 请输入API密钥")
    
    # 保存设置
    if st.button("💾 保存API配置", type="primary"):
        new_keys = {
            "openai": openai_key,
            "anthropic": anthropic_key,
            "google": google_key
        }
        
        # 过滤空值
        new_keys = {k: v for k, v in new_keys.items() if v.strip()}
        
        st.session_state.api_keys = new_keys
        
        # 保存到文件
        save_api_keys(new_keys)
        st.success("🎉 API配置已保存！")
        st.rerun()

def render_ui_settings():
    """渲染界面设置"""
    st.markdown("### 🎨 界面个性化")
    
    # 主题设置
    st.markdown("#### 🌈 主题设置")
    theme = st.radio(
        "选择主题",
        ["浅色主题", "深色主题", "自动切换"],
        index=0,
        horizontal=True
    )
    st.session_state.theme = theme
    
    # 语言设置
    st.markdown("#### 🌍 语言设置")
    language = st.selectbox(
        "界面语言",
        ["简体中文", "繁体中文", "English", "日本语"],
        index=0
    )
    st.session_state.language = language
    
    # 显示设置
    st.markdown("#### 📱 显示设置")
    col1, col2 = st.columns(2)
    
    with col1:
        font_size = st.select_slider(
            "字体大小",
            options=["小", "中", "大", "特大"],
            value="中"
        )
        st.session_state.font_size = font_size
        
        show_timestamps = st.checkbox(
            "显示时间戳",
            value=st.session_state.get("show_timestamps", True)
        )
        st.session_state.show_timestamps = show_timestamps
    
    with col2:
        show_model_badges = st.checkbox(
            "显示模型标签",
            value=st.session_state.get("show_model_badges", True)
        )
        st.session_state.show_model_badges = show_model_badges
        
        compact_mode = st.checkbox(
            "紧凑模式",
            value=st.session_state.get("compact_mode", False),
            help="减少界面元素间距"
        )
        st.session_state.compact_mode = compact_mode
    
    # 声音设置
    st.markdown("#### 🔊 声音设置")
    col1, col2 = st.columns(2)
    
    with col1:
        enable_sound = st.checkbox(
            "启用提示音",
            value=st.session_state.get("enable_sound", False)
        )
        st.session_state.enable_sound = enable_sound
    
    with col2:
        if enable_sound:
            sound_volume = st.slider(
                "音量",
                min_value=0,
                max_value=100,
                value=st.session_state.get("sound_volume", 50)
            )
            st.session_state.sound_volume = sound_volume

def render_data_management():
    """渲染数据管理"""
    st.markdown("### 💾 数据管理")
    
    # 对话管理
    st.markdown("#### 💬 对话数据")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.metric("总对话数", st.session_state.get("total_conversations", 0))
    
    with col2:
        st.metric("总消息数", st.session_state.get("total_messages", 0))
    
    with col3:
        st.metric("数据大小", "2.3 MB")
    
    # 导出数据
    st.markdown("#### 📤 数据导出")
    
    export_format = st.radio(
        "选择导出格式",
        ["JSON", "CSV", "Markdown"],
        horizontal=True
    )
    
    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("📥 导出对话记录", use_container_width=True):
            export_conversations(export_format)
    
    with col2:
        if st.button("📥 导出用户设置", use_container_width=True):
            export_settings()
    
    # 导入数据
    st.markdown("#### 📤 数据导入")
    
    uploaded_file = st.file_uploader(
        "选择要导入的文件",
        type=['json', 'csv'],
        help="支持导入之前导出的对话记录"
    )
    
    if uploaded_file:
        if st.button("📂 导入数据"):
            import_data(uploaded_file)
    
    # 清理数据
    st.markdown("---")
    st.markdown("#### 🗑️ 数据清理")
    
    st.warning("⚠️ 以下操作不可撤销，请谨慎操作")
    
    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("🗑️ 清空所有对话", type="secondary"):
            if st.session_state.get("confirm_delete_all"):
                clear_all_conversations()
                st.success("所有对话已清空")
                st.session_state.confirm_delete_all = False
            else:
                st.session_state.confirm_delete_all = True
                st.error("请再次点击确认删除")
    
    with col2:
        if st.button("🔄 重置所有设置", type="secondary"):
            if st.session_state.get("confirm_reset_all"):
                reset_all_settings()
                st.success("所有设置已重置")
                st.session_state.confirm_reset_all = False
            else:
                st.session_state.confirm_reset_all = True
                st.error("请再次点击确认重置")

def render_advanced_settings():
    """渲染高级设置"""
    st.markdown("### 🔧 高级设置")
    
    # 性能设置
    st.markdown("#### ⚡ 性能优化")
    
    col1, col2 = st.columns(2)
    
    with col1:
        max_history = st.number_input(
            "最大历史记录数",
            min_value=10,
            max_value=1000,
            value=st.session_state.get("max_history", 100),
            help="限制每个对话保留的最大消息数"
        )
        st.session_state.max_history = max_history
        
        request_timeout = st.number_input(
            "请求超时时间(秒)",
            min_value=10,
            max_value=300,
            value=st.session_state.get("request_timeout", 60)
        )
        st.session_state.request_timeout = request_timeout
    
    with col2:
        auto_save_interval = st.number_input(
            "自动保存间隔(分钟)",
            min_value=1,
            max_value=60,
            value=st.session_state.get("auto_save_interval", 5)
        )
        st.session_state.auto_save_interval = auto_save_interval
        
        max_concurrent_requests = st.number_input(
            "最大并发请求数",
            min_value=1,
            max_value=10,
            value=st.session_state.get("max_concurrent_requests", 3)
        )
        st.session_state.max_concurrent_requests = max_concurrent_requests
    
    # 安全设置
    st.markdown("#### 🔒 安全设置")
    
    enable_encryption = st.checkbox(
        "启用本地数据加密",
        value=st.session_state.get("enable_encryption", False),
        help="对本地存储的对话数据进行加密"
    )
    st.session_state.enable_encryption = enable_encryption
    
    if enable_encryption:
        encryption_key = st.text_input(
            "加密密钥",
            type="password",
            help="用于加密本地数据的密钥"
        )
        st.session_state.encryption_key = encryption_key
    
    # 开发者设置
    st.markdown("#### 👨‍💻 开发者选项")
    
    enable_debug = st.checkbox(
        "启用调试模式",
        value=st.session_state.get("debug_mode", False)
    )
    st.session_state.debug_mode = enable_debug
    
    if enable_debug:
        st.info("🐛 调试模式已启用，将显示详细的日志信息")
        
        if st.button("📊 查看系统日志"):
            show_system_logs()
        
        if st.button("🔍 检查系统状态"):
            show_system_status()

def save_api_keys(keys: dict):
    """保存API密钥到文件"""
    try:
        config_dir = Path("data/config")
        config_dir.mkdir(parents=True, exist_ok=True)
        
        with open(config_dir / "api_keys.json", "w") as f:
            json.dump(keys, f)
        
        return True
    except Exception as e:
        st.error(f"保存API密钥失败: {e}")
        return False

def export_conversations(format_type: str):
    """导出对话记录"""
    try:
        conversations = st.session_state.get("chat_history", [])
        
        if format_type == "JSON":
            data = json.dumps(conversations, ensure_ascii=False, indent=2)
            st.download_button(
                "下载JSON文件",
                data,
                file_name="conversations.json",
                mime="application/json"
            )
        elif format_type == "CSV":
            import pandas as pd
            df = pd.DataFrame(conversations)
            csv = df.to_csv(index=False)
            st.download_button(
                "下载CSV文件",
                csv,
                file_name="conversations.csv",
                mime="text/csv"
            )
        elif format_type == "Markdown":
            md_content = "# 对话记录\n\n"
            for msg in conversations:
                role = "用户" if msg["role"] == "user" else "AI助手"
                md_content += f"## {role}\n\n{msg['content']}\n\n---\n\n"
            
            st.download_button(
                "下载Markdown文件",
                md_content,
                file_name="conversations.md",
                mime="text/markdown"
            )
    except Exception as e:
        st.error(f"导出失败: {e}")

def export_settings():
    """导出用户设置"""
    try:
        settings_data = {
            key: value for key, value in st.session_state.items()
            if not key.startswith('_') and isinstance(value, (str, int, float, bool, list, dict))
        }
        
        data = json.dumps(settings_data, ensure_ascii=False, indent=2)
        st.download_button(
            "下载设置文件",
            data,
            file_name="user_settings.json",
            mime="application/json"
        )
    except Exception as e:
        st.error(f"导出设置失败: {e}")
